<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="产品名称" prop="title">
        <el-input v-model="ruleForm.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="产品简述" prop="introduction">
        <el-input v-model="ruleForm.introduction" :rows="2" type="textarea" />
      </el-form-item>
      <el-form-item label="产品详述" prop="detail">
        <el-input v-model="ruleForm.detail" :rows="2" type="textarea"> </el-input>
      </el-form-item>
      <el-form-item label="产品图片" prop="productImg">
        <Upload :avatar="ruleForm.productImg" @change="handleChange" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">添加产品</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import uploadFun from '@/util/uploadFun';
import Upload from '@/components/upload/Upload.vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const ruleFormRef = ref();
const ruleForm = reactive({
  title: '',
  introduction: '',
  productImg: '',
  detail: null,
  file: null // 上传的原生文件对象
});
const rules = reactive({
  title: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  introduction: [{ required: true, message: '请输入产品简述', trigger: 'blur' }],
  detail: [{ required: true, message: '请输入产品详述', trigger: 'blur' }],
  productImg: [{ required: true, message: '请选择产品图片', trigger: 'change' }]
});
const handleChange = (file) => {
  ruleForm.productImg = URL.createObjectURL(file);
  ruleForm.file = file;
};
const submitForm = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await uploadFun('/adminApi/product/add', ruleForm);
      if (res.code === 200) {
        ElMessage({
          message: res.msg,
          type: 'success'
        });
        router.push('/product-manage/product-list');
      }
    }
  });
};
</script>
<style lang="scss" scoped></style>
